const userUtils = require("../../utils/user");
const validate = require('../../utils/validate');
const common = require('../../utils/common');
const wxp = require('../../utils/wxp.js');
var pageUtils = require("../../utils/pageOptions.js");
const {
  getHomeData,
  getHomeTiling
} = require('../../services/home')
const {
  updateBusinessTime
} = require('../../services/stores')
const {
  shopGenerate
} = require('../../services/shop');
const defaultHomeData = {
  shopVo: {
    address: '淄博市张店区联通路128号',
    shopName: '百花园超市',
    businessTime: '09:00~21:00',
    totalAmount: 0,
    daySumIncomeAmount: 0,
    sumIncomeAmount: 0,
    dayCount: 0,
    shopRank: 0,
    codeUrl: '../../images/home_qrcode.jpg',
  }
}
Page({
  data: {
    isLogin: false,
    minPickup: 100,
    homeData: {
      shopVo: {}
    },
    shareCodeInfo: {}, //分享门店二维码信息
    tilingData: {},
    pageScrollTop: 0,
    isCodeViewShow: false,
    containerTouchmove: '',
    codeMenus: [{
        icon: '/images/index/code_md.png',
        name: '下载\n门店二维码',
      },
      {
        icon: '/images/index/code_mdhb.png',
        name: '下载\n门店海报',
      }, {
        icon: '/images/index/code_tghb.png',
        name: '下载\n推广海报',
      }
    ],
    orderMenus: [{
        name: '全部订单',
        icon: 'allOrders',
        src: '/pages/all-order-list/index'
      },
      {
        name: '今日待揽收',
        icon: 'lanshou',
        src: '/pages/collection-products/index'
      },
      {
        name: '待提货订单',
        icon: 'van',
        src: '/pages/waiting-for-pickup-list/index'
      },
      {
        name: '售后',
        icon: 'after-sales',
        src: '/pages/sell-order-list/index'
      },
    ],
    servicesMenus: [{
        name: '我的账单',
        icon: '/images/index/index_myorder.png',
        src: '/pages/bill/index'
      },
      // {
      //   name: '销量比拼',
      //   icon: '/images/index/index_sales.png',
      //   src: '/pages/sales-volume/index'
      // },
      {
        name: '快捷报单',
        icon: '/images/index/index_baodan.png',
        src: '/pages/baodan/index'
      },
      {
        name: '图文提取',
        icon: '/images/index/index_img-extract.png',
        src: '/pages/graphic-recognition/index'
      },
      // {
      //   name: '查看会员',
      //   icon: '/images/index/index_vip.png',
      //   src: '/pages/vip/index'
      // },
      {
        name: '门店录入',
        icon: '/images/index/index_addShops.png',
        src: '/pages/add-store/index'
      },
      {
        name: '我的分销',
        icon: '/images/index/index_wdsy.png',
        src: '/pages/myDistribution/index'
      },
      {
        name: '推广海报',
        icon: '/images/index/index_tghb.png',
        src: '/pages/promotePage/index'
      },
      {
        name: '联系客服',
        icon: '/images/index/index_lxkf.png',
        src: '/pages/contactService/index'
      },
      {
        name: '赚钱攻略',
        icon: '/images/index/index_zqgl.png',
        src: '/pages/makeMoney/index'
      },
    ],
    withdrawEnable: false
  },
  onLoad: function (options) {
    this.initData();
  },
  initData() {
    //清除状态
    var tmpPageOptions = pageUtils.pageOptionsInfo();
    if (tmpPageOptions) {
      pageUtils.clearPageOptionsInfo();
    }
    // 
    let userInfo = userUtils.getUserInfo();
    // 推广员
    if (userInfo.userType == 3) {
      wx.redirectTo({
        url: '/pages/promoter/promoter',
      })
    } else if (userInfo.userType == 4) {
      // 推广主管
      wx.redirectTo({
        url: '/pages/promoterManager/promoterManager',
      })
    } else {
      this.getRemoteData();
    }
  },
  // 获取首页数据
  getRemoteData({
    pullDownRefresh = false
  } = {}) {
    var requestList = [];
    //首页数据
    requestList.push(getHomeData());
    // 平铺广告
    requestList.push(getHomeTiling());
    //获取数据
    Promise.all(requestList).then(results => {
      if (pullDownRefresh) {
        wx.stopPullDownRefresh({});
      }
      //处理返回的首页数据
      this.handleHomeData(results[0]);
      //处理返回的平铺广告
      this.handleHomeTilingData(results[1]);
    }).catch(err => {
      if (pullDownRefresh) {
        wx.stopPullDownRefresh({});
      }
      common.log(err);
    });
  },
  //
  // 处理返回的平铺广告
  handleHomeData(res) {
    const userInfo = userUtils.getUserInfo()
    const isLogin = userInfo && userInfo.login
    userUtils.updateUserInfo({
      shopVo: res.data.shopVo
    })
    let homeData = {}
    if (res.data.fakePage && !isLogin) {
      homeData = {
        ...res.data,
        ...defaultHomeData
      }
    } else {
      homeData = res.data
    }
    this.setData({
      homeData,
      isLogin,
    }, this.checkWithdrawEnable)
  },
  // 处理返回的平铺广告
  handleHomeTilingData(res) {
    if (res.data) {
      this.setData({
        tilingData: {
          ...res.data
        }
      });
    }
  },

  checkWithdrawEnable: function () {
    const {
      homeData
    } = this.data
    const withdrawEnable = homeData.totalAmount >= this.data.minPickup
    this.setData({
      withdrawEnable
    })
  },
  editBusinessTime: function () {
    if (this.isFakePage()) return;
    wx.navigateTo({
      url: '/pages/timeRangeSelect/index'
    })
  },
  goWidthdraw: function () {
    if (this.isFakePage()) return;
    const {
      homeData
    } = this.data
    if (!this.data.withdrawEnable) return
    wx.navigateTo({
      url: `/pages/withdraw/index?total=${homeData.totalAmount}&bankCardNo=${homeData.shopVo.bankCardNo}`
    })
  },
  updateTimeRange: function ({
    start,
    end
  }) {
    const businessTime = `${start} ~ ${end}`
    updateBusinessTime({
      businessTime
    }).then((res) => {
      common.showToast("更新成功！")
      this.getRemoteData()
    }).catch((err) => {
      common.log(err)
    })
  },
  logout: function () {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/index'
      })
    } else {
      userUtils.removeToken()
      userUtils.updateUserInfo({
        login: false
      })
      wx.navigateTo({
        url: '/pages/login/index'
      })
    }
  },
  // 订单管理
  goOrderDetial(e) {
    let {
      src
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: src
    })
  },
  // 常用服务
  goDetial: function (e) {
    if (this.isFakePage()) return;
    let index = e.currentTarget.dataset.index;
    let item = this.data.servicesMenus[index];
    if (item.src.indexOf('makeMoney') != -1) {
      wx.navigateTo({
        url: item.src + '?id=' + this.data.homeData.cmsId
      })
    } else {
      wx.navigateTo({
        url: item.src
      })
    }
  },
  //保存到相册
  saveToAlbum: function (filePath) {
    //获取权限
    if (wx.saveImageToPhotosAlbum) {
      wxp.getSetting().then(res => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wxp.authorize({
            scope: 'scope.writePhotosAlbum'
          }).then(res => {
            //直接保存
            this.savePageImageToPhotosAlbum(filePath);
          }).catch(res => {
            //拒绝授权,打开设置
            this.openPhotosAlbumSetting(res);
          });
        } else {
          //3.写入相册
          this.savePageImageToPhotosAlbum(filePath);
        }
      }).catch(res => {
        common.log(res);
      });
    } else {
      common.showModal("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。");
    }
  },

  //提示打开相册权限
  openPhotosAlbumSetting: function (res, filePath) {
    //授权拒绝
    var firstAuthDeny = res.errMsg.indexOf("fail auth deny") != -1;
    if (firstAuthDeny) return;
    //提示打开设置
    common.showModal("亲，我们未获得您的相册授权，即将打开设置", {
      title: '',
      showCancel: true,
    }, () => {
      wx.openSetting({
        success: response => {
          var isOpenWriteAuth = response.authSetting['scope.writePhotosAlbum'];
          if (isOpenWriteAuth) {
            this.savePageImageToPhotosAlbum(filePath);
          }
        }
      })
    })
  },
  //保存图片到相册
  savePageImageToPhotosAlbum: function (filePath) {
    wx.saveImageToPhotosAlbum({
      filePath,
      success: res => {
        common.showToast("保存成功！");
      }
    });
  },
  // 邀请团长
  goGroupActivity() {
    if (this.isFakePage()) return;

    wx.navigateTo({
      url: this.data.tilingData.linkUrl
    })
  },
  // 今日订单
  onTodayOrder() {
    if (this.isFakePage()) return;
    wx.navigateTo({
      url: '/pages/todayOrder/index',
    })
  },
  // 今日顾客
  onTodayClient() {
    if (this.isFakePage()) return;
    wx.navigateTo({
      url: '/pages/todayClient/index',
    })
  },
  // 今日收益
  onTodayTic() {
    if (this.isFakePage()) return;
    wx.navigateTo({
      url: '/pages/commissionDetail/index',
    })
  },
  // 是否已经登录
  isFakePage() {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/index'
      })
      return true;
    } else {
      return false;
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getRemoteData({
      pullDownRefresh: true
    });
  },
  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    var topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () {},
  // 活动规则
  onDownloadCode() {
    this.setData({
      isCodeViewShow: true,
      containerTouchmove: 'preventTouchMove'
    })
  },
  // 取消规则弹窗
  onCodeBg() {
    this.setData({
      isCodeViewShow: false,
      containerTouchmove: ''
    })
  },
  //获取海报连接
  /**
    path 跳转路径
    platform 生成的二维码平台
    type 分享类型，1邀请团长海报，2首页海报
   */
  getShopPoster({
    path,
    platform,
    type
  }) {
    let params = {
      path: path,
      platform: platform,
      type: type,
    }
    shopGenerate(params).then(res => {
      this.setData({
        shareCodeInfo: {
          ...this.data.shareCodeInfo,
          ...{
            ['icon' + type]: res.data
          }
        }
      });
      // 保存
      this.onSavePoster(this.data.shareCodeInfo['icon' + type], type, this.data.shareCodeInfo['filePath' + type])
    }).catch(err => {
      common.log(err);
    })
  },
  // 保存海报
  /**
   * 
   * @param {*} icon 下载地址 
   * @param {*} type 海报分享类型
   * @param {*} filePath 可以保存的path
   */
  onSavePoster(icon, type, filePath) {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/index'
      })
      return
    }
    if (filePath) {
      this.saveToAlbum(filePath);
      return
    }
    common.wxDownloadFile(icon).then(res => {
      this.setData({
        shareCodeInfo: {
          ...this.data.shareCodeInfo,
          ...{
            ['filePath' + type]: res
          }
        }
      })
      this.saveToAlbum(this.data.shareCodeInfo['filePath' + type]);
    }).catch(err => {
      common.log(err);
    })
  },
  // 点击二维码
  onCodeItem(e) {
    if (e.detail.index == 0) {
      // 门店二维码
      this.onSavePoster(this.data.homeData.shopVo.codeUrl, 'er', this.data.shareCodeInfo['filePath' + 'er'])
    } else if (e.detail.index == 1) {
      // 门店海报
      this.getShopPoster({
        path: 'pages/index/index',
        platform: '1',
        type: '2'
      });
    } else if (e.detail.index == 2) {
      // 推广海报
      this.getShopPoster({
        path: 'pages/tobeTzFirstStep/tobeTzFirstStep',
        platform: '1',
        type: '1'
      });
    }
    this.onCodeBg();
  }
})
